package server.configuration;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 解析Server配置
 *
 * @author leonzhangxf
 */
public class ServerParser {

    public static void parse(Server server) {
        InputStream resourceAsStream = ServerParser.class.getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> connectorList = rootElement.selectNodes("//connector");
            Element connectorEle = connectorList.get(0);
            String port = connectorEle.attributeValue("port");

            Server.Connector connector = new Server.Connector();
            connector.setPort(Integer.parseInt(port));

            List<Element> hostList = rootElement.selectNodes("//host");
            Element hostEle = hostList.get(0);
            String name = hostEle.attributeValue("name");
            String appBase = hostEle.attributeValue("appBase");
            Server.Host host = new Server.Host();
            host.setName(name);
            host.setAppBase(appBase);

            Server.Service service = new Server.Service();
            server.setService(service);

            service.setConnector(connector);

            Server.Engine engine = new Server.Engine();
            engine.setHost(host);
            service.setEngine(engine);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
